package com.example.blog.service.impl;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.example.blog.entity.Image;
import com.example.blog.mapper.ImageMapper;
import com.example.blog.service.ImageService;

@Service
public class ImageServiceImpl implements ImageService {

    @Autowired
    private ImageMapper imageMapper;
    
    @Value("${file.upload-dir}")
    private String uploadDir;
    
    @Override
    @Transactional
    public Map<String, Object> uploadImage(MultipartFile file, Integer userId) {
        Map<String, Object> map = new HashMap<>();
        
        try {
            // 检查文件是否为空
            if (file.isEmpty()) {
                map.put("success", false);
                map.put("message", "上传的文件不能为空");
                return map;
            }
            
            // 检查文件类型
            String originalFilename = file.getOriginalFilename();
            String fileExtension = getFileExtension(originalFilename);
            if (!isImageFile(fileExtension)) {
                map.put("success", false);
                map.put("message", "只支持上传图片文件");
                return map;
            }
            
            // 生成唯一文件名
            String uniqueFilename = UUID.randomUUID().toString() + fileExtension;
            
            // 使用绝对路径确保目录正确创建
            String uploadPath = System.getProperty("user.dir") + "/uploads/images";
            Path dirPath = Paths.get(uploadPath);
            if (!Files.exists(dirPath)) {
                Files.createDirectories(dirPath);
            }
            
            // 如果是用户头像上传（userId不为空），先删除旧头像
            if (userId != null) {
                Image oldAvatar = imageMapper.selectUserAvatar(userId);
                if (oldAvatar != null) {
                    // 因为系统设计是使用最早的图片作为头像，所以只替换物理文件，不删除数据库记录
                    String basePath = System.getProperty("user.dir");
                    String oldImagePath = oldAvatar.getImagePath();
                    if (!oldImagePath.startsWith("/") && !oldImagePath.contains(":")) {
                        oldImagePath = basePath + "/" + oldImagePath;
                    }
                    
                    try {
                        // 删除旧头像文件
                        Path oldFilePath = Paths.get(oldImagePath);
                        Files.deleteIfExists(oldFilePath);
                        
                        // 生成新的文件名，但保持原始数据库记录
                        // 保存新文件到旧文件的位置，使用旧文件的文件名
                        String newFileName = oldAvatar.getImageName();
                        Path newFilePath = dirPath.resolve(newFileName);
                        file.transferTo(newFilePath.toFile());
                        
                        // 更新结果信息，使用原始记录的ID
                        map.put("success", true);
                        map.put("message", "头像更新成功");
                        map.put("imageId", oldAvatar.getImageId());
                        map.put("imageName", oldAvatar.getImageName());
                        map.put("imagePath", oldAvatar.getImagePath());
                        
                        // 提前返回，不创建新记录
                        return map;
                    } catch (IOException e) {
                        // 如果替换失败，继续创建新记录作为备选方案
                        System.err.println("替换头像文件失败，将创建新记录: " + e.getMessage());
                    }
                }
            }
            
            // 保存文件
            Path filePath = dirPath.resolve(uniqueFilename);
            file.transferTo(filePath.toFile());
            
            // 设置相对路径存储到数据库，便于前端访问
            String relativePath = "uploads/images/" + uniqueFilename;
            
            // 创建图片记录
            Image image = new Image();
            image.setUserId(userId);
            image.setImagePath(relativePath);
            image.setImageName(uniqueFilename);
            image.setCreateTime(new Date());
            image.setIsDeleted(false);
            
            // 保存到数据库
            int result = imageMapper.insert(image);
            if (result > 0) {
                map.put("success", true);
                map.put("message", "上传成功");
                map.put("imageId", image.getImageId());
                map.put("imageName", image.getImageName());
                map.put("imagePath", image.getImagePath());
            } else {
                map.put("success", false);
                map.put("message", "上传失败");
                
                // 删除已保存的文件
                Files.deleteIfExists(filePath);
            }
        } catch (IOException e) {
            map.put("success", false);
            map.put("message", "系统异常：" + e.getMessage());
        }
        
        return map;
    }

    @Override
    public Image getImageById(Integer imageId) {
        return imageMapper.selectByPrimaryKey(imageId);
    }

    @Override
    public Image getImageByName(String imageName) {
        return imageMapper.selectByImageName(imageName);
    }

    @Override
    public List<Image> getImagesByUserId(Integer userId) {
        return imageMapper.selectByUserId(userId);
    }

    @Override
    public List<Image> getNotDeletedImagesByUserId(Integer userId) {
        return imageMapper.selectNotDeletedByUserId(userId);
    }

    @Override
    public Image getUserAvatar(Integer userId) {
        return imageMapper.selectUserAvatar(userId);
    }

    @Override
    @Transactional
    public boolean markImageAsDeleted(Integer imageId) {
        try {
            int result = imageMapper.markAsDeleted(imageId);
            return result > 0;
        } catch (Exception e) {
            return false;
        }
    }

    @Override
    @Transactional
    public boolean deleteImage(Integer imageId) {
        try {
            // 获取图片信息
            Image image = imageMapper.selectByPrimaryKey(imageId);
            if (image == null) {
                return false;
            }
            
            // 获取项目路径作为基准
            String basePath = System.getProperty("user.dir");
            String imagePath = image.getImagePath();
            
            // 如果存储的是相对路径，则添加基准路径
            if (!imagePath.startsWith("/") && !imagePath.contains(":")) {
                imagePath = basePath + "/" + imagePath;
            }
            
            // 删除物理文件
            Path filePath = Paths.get(imagePath);
            Files.deleteIfExists(filePath);
            
            // 删除数据库记录
            int result = imageMapper.deleteByPrimaryKey(imageId);
            return result > 0;
        } catch (Exception e) {
            return false;
        }
    }
    
    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String filename) {
        if (filename == null) return "";
        int lastIndex = filename.lastIndexOf(".");
        if (lastIndex == -1) return "";
        return filename.substring(lastIndex);
    }
    
    /**
     * 检查是否为图片文件
     */
    private boolean isImageFile(String fileExtension) {
        if (fileExtension == null) return false;
        fileExtension = fileExtension.toLowerCase();
        return fileExtension.equals(".jpg") || fileExtension.equals(".jpeg") || 
               fileExtension.equals(".png") || fileExtension.equals(".gif") || 
               fileExtension.equals(".bmp");
    }
} 